rm(list = ls())

library(tidyverse)

## Helper function

state_id_to_names <- function(state_id) {
  names <- recode(state_id,
    `01` = "Schleswig-Holstein", `02` = "Hamburg",
    `03` = "Niedersachsen", `04` = "Bremen", `05` = "North Rhine-Westphalia",
    `06` = "Hesse", `07` = "Rhineland-Palatinate", `08` = "Baden-Württemberg",
    `09` = "Bavaria", `10` = "Saarland", `11` = "Berlin",
    `12` = "Brandenburg", `13` = "Mecklenburg-Vorpommern",
    `14` = "Saxony", `15` = "Saxony-Anhalt", `16` = "Thuringia"
  )
  return(names)
}

## Load Data

## Federal data

btw <- readRDS("data/data_main.RDS") %>%
  mutate(unit = "Federal election") %>%
  mutate(state = substr(county_id_2018, 1, 2)) %>%
  filter(!year == 2013)

## Municipal data

muni <- readRDS('data/data_main_municipal.RDS')%>% 
  mutate(unit = 'Municipal election') 

## Add 1980 (first election but not in data due to first differences)

btw80 <- btw %>% 
  filter(year == 1983) %>% 
  distinct(state,  unit, .keep_all = T) %>% 
  mutate(year = 1980)

btw <- btw %>%
  bind_rows(btw80)

## Combine data sets, prep for plotting

df <- bind_rows(btw, muni) %>%
    ungroup() %>%
    dplyr::select(state, year, unit, treat_categorical4) %>%
    distinct(state, year, unit) %>%
    filter(!is.na(state)) %>%
    mutate(state_name = state_id_to_names(state)) %>%
    filter(!is.na(state_name)) %>%
    mutate(state = as.numeric(state)) %>%
    mutate(state_name = fct_reorder(state_name, state, .desc = T)) %>%
    filter(!year < 1983) %>%
    filter(!(year == 1990 & state > 10))

## Breaks only when there are elections 

b_list <- df %>% pull(year) %>% unique()

## ##

p1 <- ggplot(df, aes(state_name, year, unit)) +
  geom_point(aes(shape = unit, color = unit, fill = unit),
    position = position_dodge(0.65),
    size = 3
  ) +
  theme_bw() +
  xlab("Federal state") +
  ylab("Year") +
  coord_flip() +
  scale_y_continuous(breaks = b_list) +
  theme(axis.text.x = element_text(
    angle = 90, vjust = 0.5,
    hjust = 1
  )) +
  theme(panel.grid.major.x = element_line()) +
  scale_color_grey(name = "", end = 0.7) +
  scale_fill_grey(name = "", end = 0.7) +
  scale_shape_manual(
    values = c(19, 22, 23),
    name = ""
  ) +
  theme(legend.position = "bottom")
p1
